<?php
/**
 * Created by coder meng.
 * User: coder meng
 * Date: 2018/4/9 13:46
 */
namespace app\home\controller;
use cmf\controller\HomeBaseController;
use app\home\model\PayModel as PAY;
use think\Db;
class OrderpayController extends HomeBaseController
{
    /*
     * 操作员信息
     * */
    public function session()
    {
        $session=cmf_get_current_user();
        return $session;
    }
    /*
     * 会员信息
     *
     * */
    public function user($phone,$shopid)
    {
        $where['mobile']=$phone['mop'];
        $where['store_id']=array('in',$shopid);
        $data=DB::name('member')->where($where)->find();
        $array['userid']=$data['id'];
        $array['cartid']=$data['card_id'];
        return $array;
    }
    /*
     *菜单选择
     * */
    public function index()
    {
        return $this->fetch();
    }
    /*
     * 单品
     * 提交订单
     * 规格没有整理
     * 2018-05-31 会员价 判断会员价是否开启 开启+登录人是会员了才享受会员价
     * 改价商品不与会员价商品享受同一个功能，同时也不与折扣商品一起享受会员价
     * */
    public function paytype()
    {
        if($_POST)
        {
            session_start();
            $vip=$_POST['vip'];
            $all_money=$_POST['all_money'];
            $up=$_POST['up'];
            $where['orderNo']=$_POST['order'];
            $switch=DB::name('switch')->where(['vipprice_status'=>1])->find();
            $order=DB::name('order')->where($where)->find();
            if($order)
            {
                $data['money']=$order['totalMoney'];
            }else{
                $data['money']='';
            }
            if($switch)
            {

                if(!empty($_SESSION['think']['phoneone']))
                {
                    if($up == 1)
                    {
                        $data['status']=0;
                        $data['all_money']=$all_money;
                    }else{
                        $data['status']=1;
                        $data['vip']=$vip;
                    }
                }else{
                    $data['status']=0;
                    $data['all_money']=$all_money;
                }
            }else{
                $data['status']=0;
                $data['all_money']=$all_money;
            }
            $this->success($data);
        }else{
            return $this->fetch('shop/jiesuan');
        }

    }
    /*
     * 支付
     * 判断支付方式（完）
     * 判断是否是会员（完）
     * 判断会员是否认证（完）
     * 是会员了查找比例设置 购买多少钱赠送多少积分
     * 是会员的话多少积分抵扣多少钱（）
     * */
    public function pay()
    {
        session_start();
        $order=$_POST['order'];
        $state=$_POST['state'];
        $s_pay=$_POST['s_pay'];
        $data['order']=$order;
        $data['s_pay']=$s_pay;
        $data['state']=$state;
        $orpay=new PAY();
        $session=$this->session();
        $shop_id=manage($session['store_id']);
        $data['shopid']=$session['store_id'];
		session('order',$order);
        if(!empty($_SESSION['think']['phoneone']))
        {
            $ses=$_SESSION['think']['phoneone'];
            $member=$this->user($ses,$shop_id);
            $where['cardid']=$member['cartid'];
            $where['userid']=$member['userid'];
            $where['storeid']=array('in',$shop_id);
			session('order',$order);
            $use=DB::name('finance')->where($where)->find();

            if($state==1)
            {    
                if($use)
                {
                    if(!empty($ses['sate'])) {
                        if ($use['money'] > $s_pay || $use['money'] == $s_pay) {
                            $where['id'] = $use['id'];
                            $user_state=1;//是否是会员
                            $states = $orpay->pay($data, $where,$user_state);
                        } else {
                            $states['sate'] = 0;
                            $states['con'] = '您的余额不足';
                        }
                    } else {
                        $states['sate'] = 0;
                        $states['con'] = '您还没有认证';
                    }
                }else{
                    $states['sate'] = 0;
                    $states['con'] = '您还不是会员，不能使用余额支付';
                }
            }
            if($state==2)
            {   
                $data['cash']=$_POST['cash'];
                $data['giveChange']=$_POST['giveChange'];
                if($use)
                {   
                    $where['id']=$use['id'];
                    $user_state=1;//是否是会员
                    $states=$orpay->pay($data,$where,$user_state);
		       
                }
            }
            /*
             * 积分
             * 全积分支付的不进行购物赠送积分
             * 查询整单是否全部积分兑换完毕
             * */
            if($state==3)
            {
                    $orders=DB::name('order_detail')->where(['orderid'=>$order,'integral'=>0])->select()->toArray();
                    if($orders)
                    {
                        $states['sate'] = 0;
                        $states['con'] = '订单没有全部兑换完';

                    }else{
                        $where['id']=$use['id'];
                        $user_state=1;//是否是会员
                        $states=$orpay->pay($data,$where,$user_state);
                    }

            }
            /*
             * 微信
             * */
            if($state==4)
            {
                    $where['id']=$use['id'];
                    $user_state=1;//是否是会员
                    $states=$orpay->pay($data,$where,$user_state);
            }
            /*
             * 支付宝
             * */
            if($state==5)
            {
                $where['id']=$use['id'];
                $user_state=1;//是否是会员
                $states=$orpay->pay($data,$where,$user_state);
            }
            /*
             * 外卖
             * */
            if($state==6)
            {
                $states['sate'] = 0;
                $states['con'] = '暂时不支持会员外卖支付';
            }
        }else{
			if($state==1)
			{
				  $states['sate'] = 0;
                  $states['con'] = '您还不是会员，不能使用余额支付';
			}
			if($state==2){
		           $where=0;
				$user_state=0;
				$data['cash']=$_POST['cash'];
				$data['giveChange']=$_POST['giveChange'];
				$states=$orpay->pay($data,$where,$user_state);		
			}
            if($state == 3){
                $states['sate'] = 0;
                $states['con'] = '您还不是会员，不能使用积分支付';
            }
            if($state==4){
                $where=0;
                $user_state=0;
                $states=$orpay->pay($data,$where,$user_state);
            }
            if($state==5){
                $where=0;
                $user_state=0;
                $states=$orpay->pay($data,$where,$user_state);
            }
            if($state==6)
            {
                $where=0;
                $user_state=0;
                $states=$orpay->pay($data,$where,$user_state);
            }
        }
        $states['orderid']=$order;
        $this->success($states);
    }
    /*
     *兑换
     * */
    public function  amend()
    {
      if($_POST)
      {
          $order=$_POST['order'];
          $where['orderid']=$order;
          $where['stemeal']=0;
          $data=DB::name('order_detail')->where($where)->select()->toArray();
          return $this->success($data);
      }else{
          return $this->fetch('shop/order');
      }
    }
    /*
     * 首先查看积分是是否足够
     * 在进行扣除
     * */
    public function Integral()
    {
        session_start();
        if(!empty($_SESSION['think']['phoneone'])){
            $ses=$_SESSION['think']['phoneone'];
            $pay=new PAY();
            $oid=$_POST['oid'];
            $session=$this->session();
            $shop_id=manage($session['store_id']);
            $member=$this->user($ses,$shop_id);
            $cofig=$pay->setintegral($session['store_id']);
            $member['storeid']=$shop_id;
            $storeid=$session['store_id'];
            $money=$pay->user('integral',$member);
            $order=DB::name('order_detail')->where(['id'=>$oid,'integral'=>1])->find();
            if(!empty($ses['sate']))
            {
                if($order)
                {
                    $dat['num']=0;
                    $dat['con']='订单已经兑换成功了';
                    return $this->success($dat);
                }else{
                    if($cofig['state']==1 && $cofig['deduction'] != 0)
                    {
                        if($money['num']>$cofig['deduction']||$money['num']==$cofig['deduction'])
                        {
                            $num=$money['num']-$cofig['deduction'];
                            $integral=$pay->integral('xiaofei',$member,$storeid,$num,$oid,$cofig['deduction']);
                            $where['id']=$oid;
                            $date['integral']=1;
                            $data=DB::name('order_detail')->where($where)->find();
                            DB::name('order_detail')->where($where)->update($date);
                            $orderid=$data['orderid'];
                            $order=DB::name('order')->where(['orderNo'=>$orderid])->find();
                            $array['actualMoney']=$order['actualMoney']-$data['price'];
                            $sate=DB::name('order')->where(['orderNo'=>$orderid])->update($array);
                            $dat['num']=1;
                            $dat['con']=$order['actualMoney']-$data['price'];
                            return $this->success($dat);
                        }else{
                            $dat['num']=0;
                            $dat['con']='不好意思积分不足';
                            return $this->success($dat);
                        }
                    }else{
                        $dat['num']=0;
                        $dat['con']='积分兑换还没有开启';
                        return $this->success($dat);
                    }
                }
            }else{
                $dat['num']=0;
                $dat['con']='会员还没有没有认证，请先认证';
                return $this->success($dat);
            }
        }else{
            $dat['num']=0;
            $dat['con']="没有该会员！";
            return $this->success($dat);
        }
    }
	 public function printto(){
      
	    $dingdan=$_POST['order'];
        $order = array(
            "Name" => "Order",
            "Cols" => array(
                array( "type" => "str",  "size" => 20,  "name" => "订单号",  "required" => false ),
                array( "type" => "datetime",  "size" => 0,  "name" => "付款时间",  "required" => false ),
                array( "type" => "float",  "size" => 0,  "name" => "数量",  "required" => false ),
                array( "type" => "str",  "size" => 50,  "name" => "收银员",  "required" => false ),
                array( "type" => "float",  "size" => 0,  "name" => "现金",  "required" => false ),
                array( "type" => "float",  "size" => 0,  "name" => "合计",  "required" => false ),
                array( "type" => "float",  "size" => 0,  "name" => "优惠",  "required" => false ),
                array( "type" => "float",  "size" => 0,  "name" => "应收",  "required" => false ),
                array( "type" => "float",  "size" => 0,  "name" => "实收",  "required" => false ),
                array( "type" => "float",  "size" => 0,  "name" => "找零",  "required" => false ),                        
            ),
            "Data" => array(),            
        );
        
        
        $OrderDetail = array(
            "Name" => "OrderDetail",
            "Cols" => array(               
                array( "type" => "str",  "size" => 20,  "name" => "订单号",  "required" => false ),//这里面的都
                array( "type" => "str",  "size" => 250,  "name" => "品名",  "required" => false ),
                array( "type" => "float",  "size" => 0,  "name" => "数量",  "required" => false ),
                array( "type" => "float",  "size" => 0,  "name" => "价格",  "required" => false ),
                array( "type" => "float",  "size" => 0,  "name" => "金额",  "required" => false ),
            ),
            "Data" =>array(),
        );
        
        
        //$dingdan = '6020180509111700';//订单号 
        $liuliu = Db::name('order')->where('orderNo','in',$dingdan)//查出来的数据好像不能写在刚才那个里面吧 要用下面的
                ->alias('a')->join('__USER__ b','a.operatorid=b.id','left')
                ->join('__ORDER_DETAIL__ c','a.orderNo=c.orderid','left')
                ->field('a.*,b.user_login,a.orderNo,c.g_goodsname,a.payType,a.getMoney,a.totalMoney,a.discount,a.actualMoney,a.actualMoney,a.giveChange,c.price,a.ctime')->select();
        
        //$OrderDetail['Data'] = $liuliu;     //如果查询出来的结果集跟字段定义一一对应，则可以这样

        //如果是从数据库中查询出来，这里就改成取数
        $order["Data"] = array(
            array(
                "订单号" =>$dingdan,
                "付款时间" => $liuliu[0]["ctime"],
                "数量" =>1,
                "收银员" =>$liuliu[0]["user_login"],
                "现金" =>$liuliu[0]["getMoney"],
                "合计" =>$liuliu[0]["totalMoney"],
                "优惠" =>$liuliu[0]["discount"],
                "应收" =>$liuliu[0]["actualMoney"],
                "实收" =>$liuliu[0]["actualMoney"],
                "找零" =>$liuliu[0]["giveChange"],
            ),
        );
        

        //如果查询出来的结果集跟上面定义的不一一对应，则可以采用下面的方式
        foreach ($liuliu as $row) {
            $_r = array(
                "订单号" => $row["user_login"],
                "品名" => $row["g_goodsname"],
                "数量" => 1,
                "价格" => $row["price"],
                "金额" => $row["price"],          
            );
            $OrderDetail['Data'][] = $_r;
        }
        //总集成
        $data = array(
            "template" => "nihao.fr3",
            "Ver" => "4.0",
            "Tables" => array(
                $order,
                $OrderDetail
            ),
        );
        //转成json
        //json_encode($data);
        $jsonStr = json_encode($data);
        //var_dump($jsonStr);exit;//到这下面的就不执行了
        return $this->success($jsonStr);
        
//        
//        $to = explode(",", $liuliu);
//        //$qiqi =  Db::name('order')->where('orderNo','in',$dingdan)
//            //->alias('a')->join('__ORDER_DETAIL__ c','a.orderNo=c.orderid','left')
//                //->field('a.*,c.g_goodsname,c.price')->select()->column('c.g_goodsname,c.price');
//                //->column('c.g_goodsname,c.price');
//        var_dump($to);exit;  //这个dump出来人东西给去看
//        $rows = array();
    }
	public function printlist(){
		return $this->fetch("shop/printlist");
	}
}